<?php
class MenusController extends AppController {
	public $name = 'Menus';
	public $uses=array('Menu','Aro','Aco','Project');	
	
	function admin_index(){
		//get filter field
		$filterField=array(				
			$this->uses[0].'.name'=>_resource('news',true),
			'Projects.title'=>_resource('title',true),	
		);

		
		$this->set('filterField',$filterField);
		
		$this->render('admin_index','ajax');
	}	
	
	function admin_lists(){
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>50,
				'conditions'=>'',
				'fields'=>null,
				'order'=>'lft',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);			
		}
		
		
		
		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//===================================================================
		
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ... 
		$this->paginate=$this->Session->read($this->uses[0]);				
		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$data0=$this->paginate($this->uses[0]);
		unset($data0[0]);
		//edit for retrieve tree
		$tree=$this->{$this->uses[0]}->generateTreeList(null,null,null,'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
		foreach($data0 as $k=>$v){
			$data0[$k][$this->uses[0]]['name']=$tree[$data0[$k][$this->uses[0]]['id']];
			$data0[$k][$this->uses[0]]['methodList']=$this->admin_getMethodList($data0[$k][$this->uses[0]]['controller']);
		}		
		
		
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);
		
		$this->set('controllerList',$this->admin_getControllerList());
		$this->set('methodList',$this->admin_getMethodList());
		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website. 
		$this->render('admin_lists','ajax');
	}
	
	function admin_add($locale=null){
		//t($this->data);
		//su dung khi site co chuc nang da ngon ngu==========================
		//neu khong truyen vao ngon ngu thi ngon ngu mac dinh cua data duoc them vao se la ngon ngu duoc doc tu session
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		//khai bao ngon ngu cua model, khi do, ngon ngu cua data duoc luu vao database la $locale 
		$this->{$this->uses[0]}->locale=$locale;
		//====================================================================		
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){

				if(!($this->data[$this->uses[0]]['parent_id']))$this->data[$this->uses[0]]['parent_id']=1;
				if($this->{$this->uses[0]}->save($this->data)) {
					$this->data=null;
					
					$isInsert=true;
					$this->Session->write('message',_resource('insert data successful',true));
				} else {
					$this->Session->write('error',_resource('can not insert data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}
		
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('listLang',$this->Common->listCountry());
		//get tree
		$tab="__";
		$tree=$this->{$this->uses[0]}->generateTreeList(null,null,null,$tab);
		$this->set('tree',$tree);
		
		$this->set('isInsert',$isInsert);
	}

	function admin_edit($id=null,$locale=null){	
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		$this->{$this->uses[0]}->locale=$locale;	
		$isInsert=false;
		
		if(!empty($this->data)){
			//t($this->data);
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				//lay hinh tu array
				if(!($this->data[$this->uses[0]]['parent_id']))$this->data[$this->uses[0]]['parent_id']=1;
				if($this->{$this->uses[0]}->save($this->data)) {
					$this->data=null;
					
					$isInsert=true;
					$this->Session->write('message',_resource('update data successful',true));						
					
				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			if($id!=null){

				//get data from default language
				if($this->{$this->uses[0]}->locale!=$this->Session->read('adminLang')){
					$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
					$this->data =$this->{$this->uses[0]}->read(null,$id);
					$this->{$this->uses[0]}->locale=$locale;
					$data =$this->{$this->uses[0]}->read(null,$id);
					//get data of current select language
					foreach($this->{$this->uses[0]}->actsAs['Translate'] as $k=>$v){						
						$this->data[$this->uses[0]]['default'.$v]=$this->data[$this->uses[0]][$v];
						$this->data[$this->uses[0]][$v]=$data[$this->uses[0]][$v];
					}					
				}
				else{
					$this->data =$this->{$this->uses[0]}->read(null,$id);
				}
				
				if(empty($this->data)){	
					$this->Session->write('error',_resource('data not found',true));				
					$this->render('admin_editNotFound');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('admin_edit_not_found');
			}
		}	

		
		
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('listLang',$this->Common->listCountry());
		//get tree
		$tab="__";
		$tree=$this->{$this->uses[0]}->generateTreeList(null,null,null,$tab);
		$this->set('tree',$tree);
		
		$this->set('isInsert',$isInsert);
	}

	function admin_delete($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('delete from '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' where id in ('.implode(',',array_keys($id_arr)).')' );			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();	
	}
	
	function admin_moveUp($id=null){
		if(intval($id)){			
			$this->{$this->uses[0]}->moveUp($id);		
		}
		$this->admin_lists();
	}
	
	function admin_moveDown($id=null){
		if(intval($id)){			
			$this->{$this->uses[0]}->moveDown($id);		
		}
		$this->admin_lists();
	}
	
	function admin_published($id=null,$value=1,$field=0){
	$id_arr=null;
		$all=false;		
		switch($field){
			case 1: $fieldname='best';break;
			case 2: $fieldname='bestbuy';break;
			default: $fieldname='published';
		}
		if((!intval($value) && $value!=0) || intval($value)>1){
			$value=1;
		}
		
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
			$all=true;
		} 
		
		//if url
		if(intval($id) && !$all){
			$id_arr[$id]='';
		}
		
		if(count($id_arr)>0){			
			$this->{$this->uses[0]}->query('update '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' set '.$fieldname.'='.$value.' where id in ('.implode(',',array_keys($id_arr)).')' );
		}
		if (!$all) {			
			$this->set('value',$value);
			$this->set('field',$field);
			$this->set('fieldname',$fieldname);
			$this->set('id',intval($id));
			$this->render('admin_published','ajax');		
		} else {
			$this->admin_lists();
		}
		
	}
	
	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}
	
	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists();
	}
	
	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
	if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}
	
/*
	 * ham dung khi co su dung chuc nang da ngon ngu
	 * dung de change locale cua he thong
	 * tham so truyen vao la locale cua ngon ngu
	 */
	function admin_changeLocale($locale=null){
		//luu session
		if($locale){
			$this->Session->write('adminLang',$locale);
		}
		//reload lai luoi de apply locale vua change
		$this->admin_lists();
	}
	
	function admin_getMenu(){
		
		$menu=$this->Menu->find('all',array('order'=>'lft'));
		//t($menu);
		$realMenu=array();
		$stack=array();//stack cua node, dung de chua node cha va xac dinh cap do cua node
		$htmlMenu='<ul id="nav" class="dropdown dropdown-horizontal">';
		//stack cho node root
		$menu[0]['Menu']['html']='';
		$stack[] = $menu[0]['Menu'];
		$realMenu[]=$menu[0];
		//unset node root
		unset($menu[0]);
	 	foreach ($menu as $k => $v) {
	 		//html cho node cha
			$htmlChild='';
			//check co phai la node cha hay ko
			$isParent=false;
			
			
	 		//neu right cua node hien tai lon hon right cua node cuoi cung trong stack thi se remove node trong stack
			while (($stack[count($stack) - 1]['rght'] < $v['Menu']['rght'])) {				
				//neu node trong stack co hien ra roi thi dong tag li.
				if(isset($stack[count($stack) - 1]['isDisplay'])){
					//xet neu la node cha thi tao parent class
					if(isset($stack[count($stack) - 1]['isParent'])){						
						if($stack[count($stack) - 1]['html']!='')$stack[count($stack) - 2]['html'].='<li class="dir"><a href="javascript:;" onclick="'.$stack[count($stack) - 1]['action'].'">'._resource($stack[count($stack) - 1]['name'],true).'<ul>'.$stack[count($stack) - 1]['html'].'</a></ul></li>';
					}
					else{
						$stack[count($stack) - 2]['html'].=$stack[count($stack) - 1]['html'];
					}							
										
				}
				//t($stack,0);
				//t($stack[count($stack) - 1]['html'].'\r\n',0);	
				//remove node
				array_pop($stack);
			}
			
			//check permission
			//get user
			$user=$this->Auth->user();			
			//get group (aro)
			$group =& $this->Group;
			$group->id=$user['group_id'];	
			//t($group);
			
			//check, neu alias =null la menu cha
			$check=false;
			//check permision
			if(Configure::read('Permission.isCheck') && $group->id){
				if($v['Menu']['controller']!=null || $check){
					//xac dinh xem action co trong nhung action ko can check
					if(in_array($v['Menu']['method'],$this->Common->baseMethod()) || in_array($v['Menu']['controller'],$this->Common->baseController()) || in_array($v['Menu']['controller'].'/'.$v['Menu']['method'],$this->Common->baseMethodController())){
						$check=true;					
					}
					else{
						
						//lay alias cua aco de check permission
						$alias=$v['Menu']['controller'];
						if($v['Menu']['method']!=null)$alias.='/'.$v['Menu']['method'];																				
						$check=$this->Acl->check($group,$alias,'read');				
						
					}
				}
			}	
			else{
				$check=true;
			}				
			

			//build html			
			if($v['Menu']['url']){
				//neu la action thi do la ajaxSubmit
				if(!$v['Menu']['isLink']){
					$action='ajaxSubmit(\'mainContent\',\''.$v['Menu']['url'].'\')';		
				}
				else{
					$action='window.location=\''.$v['Menu']['url'].'\'';
				}
			}
			else{
				$action='';
			}
			$v['Menu']['action']=$action;	 		
			//neu la node con co node con thi set node la parent				
			if($k<count($menu) && $v['Menu']['rght']>$menu[$k+1]['Menu']['rght']){
				$v['Menu']['isParent']=1;
				$v['Menu']['html']='';
								
			}
			else{
				$v['Menu']['html']='<li onclick="'.$action.'"><a href="javascript:;" >'._resource($v['Menu']['name'],true).'</a></li>';
			}
			if($v['Menu']['controller']==null || $check)$v['Menu']['isDisplay']=1;
			
			
			//custome menu
			if($v['Menu']['name']=='Project'){
				$v['Menu']['html']='';
				$v['Menu']['isParent']=1;
				//get all open project
				$conditions['Status.published']=1;	
				if(!(Configure::read('Session.isAdmin') || Configure::read('Session.isSa'))){			
					$conditions['OR']=array(
						'LEFT(Project.users,'.(strlen($user['id'])+1).')'=>array($user['id'].',',$user['id']),				
						'RIGHT(Project.users,'.(strlen($user['id'])+1).')'=>array(','.$user['id'],$user['id']),
						'Project.users LIKE'=>'%,'.$user['id'].',%'
					);
				}
				$this->Project->recursive=0;
				$projs=$this->Project->find('all',array('conditions'=>$conditions));
				foreach($projs as $kp=>$vp){
					$v['Menu']['html'].='<li onclick="ajaxSubmit(\'mainContent\',\'tasks/index/'.$vp['Project']['id'].'\')"><a href="javascript:;" >'.$vp['Project']['name'].'</a></li>';
				}
			}
			
			//stack lai node hien tai de cho lan check sau co phai la node cha hay ko
			$stack[] = $v['Menu'];
		}
		//build html menu
		$htmlChild='';
		while (count($stack) > 1 ) {				
			//neu node trong stack co hien ra roi thi dong tag li.
				if(isset($stack[count($stack) - 1]['isDisplay'])){
					//xet neu la node cha thi tao parent class
					if(isset($stack[count($stack) - 1]['isParent'])){
						$stack[count($stack) - 2]['html'].='<li class="dir">'._resource($stack[count($stack) - 1]['name'],true).'<ul>'.$stack[count($stack) - 1]['html'].'</ul></li>';												
					}
					else{
						$stack[count($stack) - 2]['html'].=$stack[count($stack) - 1]['html'];
					}
					//luu html cua node hien tai vao node cha cua no
					
					//pop stack dong thoi dong tag li cua menu	
							
										
				}
				//t($stack,0);
				//t($stack[count($stack) - 1]['html'].'\r\n',0);	
				//remove node
				array_pop($stack);
		}
		//t($stack[0]['html']);
		$htmlMenu.=$stack[0]['html'].'</ul>';		
		$this->set('data',$htmlMenu);
	}

	function admin_getControllerList(){
        $data= $this->{$this->uses[2]}->find("list",array(    
        	'conditions'=>$this->uses[2].'.parent_id =1',        
            'fields' => array(str_replace('{n}.','',$this->uses[2].'.alias'), str_replace('{n}.','',$this->uses[2].'.alias'))
        ));
        return $data;
	}
	function admin_getMethodList($name=null){
		//find parent id
		$this->{$this->uses[2]}->recursive=0;
		$data=$this->{$this->uses[2]}->find('first',array(
			'conditions'=>$this->uses[2].'.alias ="'.$name.'"'
		));		
		if(isset($data[$this->uses[2]]['id']))$parent_id=$data[$this->uses[2]]['id'];
		$data=null;
		if(isset($parent_id)){		
	        $data= $this->{$this->uses[2]}->find("list",array(    
	        	'conditions'=>$this->uses[2].'.parent_id="'.$parent_id.'"',        
	            'fields' => array(str_replace('{n}.','',$this->uses[2].'.alias'), str_replace('{n}.','',$this->uses[2].'.alias'))
	        ));
		}
        return $data;
	}
	
	function admin_changeMethodList($id=null,$name=null){
		$data=null;
		if($name)$data=$this->admin_getMethodList($name);
		$this->set('id',$id);
		$this->set('data',$data);
		$this->render('admin_changeMethodList');
	}	
	
	function admin_selCat($id=null) {
		//kiem tra neu submit tu form
		//luu dieu kien chon
		$conditions=null;
		$conditions=$this->Session->read($this->uses[0].'.conditions');
		$conditions[$this->uses[0].'.category_id']=intval($id);
		if($id!=null){			
			//luu sesssion de giu lai gia da chon
			$this->Session->write($this->uses[0].'.catid',intval($id));
		}
		else{	
			$this->Session->write($this->uses[0].'.catid','');	
			unset($conditions[$this->uses[0].'.category_id']);
		}
		$this->Session->write($this->uses[0].'.conditions',$conditions);
		$this->admin_index();
	}
	
	/*
	 * ham dung de save thu tu cua tung mau tin
	 */
	function admin_save(){
		
		if(isset($this->data[$this->uses[0]]['controller'])){		
			foreach($this->data[$this->uses[0]]['controller'] as $k=>$v){
				if(intval($k)){
					//set view order for category
					$this->{$this->uses[0]}->updateAll(
					array(
						$this->uses[0].'.controller'=>'"'.$this->data[$this->uses[0]]['controller'][$k].'"',
						$this->uses[0].'.method'=>'"'.$this->data[$this->uses[0]]['method'][$k].'"',
						$this->uses[0].'.isLink'=>intval($this->data[$this->uses[0]]['isLink'][$k]),
						$this->uses[0].'.url'=>'"'.$this->data[$this->uses[0]]['url'][$k].'"'
						),
					array(
						$this->uses[0].'.id'=>$k
						)
					);
				}
			}
		}
		$this->Session->write('message',_resource('Menu has been update',true));
		$this->admin_lists();
	}
	
	
}
?>
